// 向content-script主动发送消息
function sendMessageToContentScript(message, callback) {
	getCurrentTabId((tabId) =>{
		chrome.tabs.sendMessage(tabId, message, function(response) {	
			if(callback) callback(response);
		});
	});
}
//-------------------- 右键菜单演示 ------------------------//
let devTools = [
	{
		title: 'JSON.CN',
		url: 'http://json.cn',
	},
	{
		title: 'Echarts',
		url: 'https://echarts.apache.org/zh/index.html',
	}
];
let serverList = [
	{
		title: '123服务器',
		url: 'http://bt.kblue.site:2580/bt-admin/',
	},
	{
		title: '123',
		url: ''
	}
]
let other = [
	{	
		title: '8080服务',
		url: 'http://localhost:8080',
	},
	{
		title: 'Pan',
		url: 'https://pan.kblue.site',
	},
	{
		title: 'Fast Github',
		url: 'https://hub.fastgit.org/',
	},
	{
		title: '公司服务器地址',
		url: 'http://192.168.201.159:8088/',
	},
	{
		title: '蓝湖',
		url: 'https://lanhuapp.com/web/#/item',
	}
]
axios.get('https://www.fastmock.site/mock/064c5a98f942b6d2c288d75c4c0851ce/subscribe/order').then((res) => {
	if (res.status === 200) {
		devTools = res.data.data.devTools || devTools;
		serverList = res.data.data.devTools || devTools;
		other = res.data.data.other || other;
		createMenu();
	}
})
chrome.contextMenus.create({
	title: "Github文件加速下载",
	contexts: ['link'],
	id: '01',
	onclick: function(info, tab){
		const linkUrl= info.linkUrl;
		const relUrl = `https://github.91chifun.workers.dev/${linkUrl}`;
		const msg = {
			type: 'download',
			url: relUrl,
		}
		sendMessageToContentScript(msg, (response) => {});
	}
});
chrome.contextMenus.create({
	title: "GH加速",
	contexts: ['link'],
	id: '02',
	parentId: '01',
	onclick: function(info, tab){
		const linkUrl= info.linkUrl;
		const relUrl = `https://gh.api.99988866.xyz/${linkUrl}`;
		const msg = {
			type: 'download',
			url: relUrl,
		}
		sendMessageToContentScript(msg, (response) => {});
	}
});
chrome.contextMenus.create({
	title: "91chifun加速",
	contexts: ['link'],
	id: '03',
	parentId: '01',
	onclick: function(info, tab){
		const linkUrl= info.linkUrl;
		const relUrl = `https://github.91chifun.workers.dev/${linkUrl}`;
		// https://gh.api.99988866.xyz/
		// chrome.tabs.create({url: relUrl});
		const msg = {
			type: 'download',
			url: relUrl,
		}
		sendMessageToContentScript(msg, (response) => {});
	}
});
chrome.contextMenus.create({
	title: "打开导航",
	contexts: ['page'],
	onclick: function(info){
		chrome.tabs.create({url: 'https://helson-lin.cn'});
	}
});
chrome.contextMenus.create({
	title: '清除Cookie',
	contexts: ['page'],
	onclick: function() {
		chrome.cookies.getAllCookieStores(function(cookieStores) {
			cookieStores.forEach((cookie) => {
				alert(JSON.stringify(cookie.id));
				chrome.cookies.remove({
					storeId: cookie.id 
				})
			})
		});
	}
})

function createMenu() {
	// devloper tools
	chrome.contextMenus.create({
		id: "011",
		title: "DevTools",
		contexts: ['page']
	});
	devTools.forEach((tool, index) => {
		const options = {
			id: `01${index + 2}`,
			parentId: '011',
			title: tool.title,
			contexts: ['page'],
			onclick: (params) => {
				chrome.tabs.create({url: tool.url});
			}
		}
		chrome.contextMenus.create(options);
	});
	// otherList
	other.forEach((tool, index) => {
		const options = {
			id: `03${index + 2}`,
			title: tool.title,
			contexts: ['page'],
			onclick: (params) => {
				chrome.tabs.create({url: tool.url});
			}
		}
		chrome.contextMenus.create(options);
	});
}

//-------------------- badge演示 ------------------------//
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse)
{
	console.log('收到来自content-script的消息：');
	console.log(request, sender, sendResponse);
	sendResponse('我是后台，我已收到你的消息：' + JSON.stringify(request));
});

$('#test_cors').click((e) => {
	$.get('https://www.baidu.com', function(html){
		console.log( html);
		alert('跨域调用成功！');
	});
});

$('#get_popup_title').click(e => {
	var views = chrome.extension.getViews({type:'popup'});
	if(views.length > 0) {
		alert(views[0].document.title);
	} else {
		alert('popup未打开！');
	}
});

// 获取当前选项卡ID
function getCurrentTabId(callback)
{
	chrome.tabs.query({active: true, currentWindow: true}, function(tabs)
	{
		if(callback) callback(tabs.length ? tabs[0].id: null);
	});
}

// 当前标签打开某个链接
function openUrlCurrentTab(url)
{
	getCurrentTabId(tabId => {
		chrome.tabs.update(tabId, {url: url});
	})
}

// 新标签打开某个链接
function openUrlNewTab(url)
{
	chrome.tabs.create({url: url});
}

// omnibox 演示
chrome.omnibox.onInputChanged.addListener((text, suggest) => {
	console.log('inputChanged: ' + text);
	if(!text) return;
	if(text == '美女') {
		suggest([
			{content: '中国' + text, description: '你要找“中国美女”吗？'},
			{content: '日本' + text, description: '你要找“日本美女”吗？'},
			{content: '泰国' + text, description: '你要找“泰国美女或人妖”吗？'},
			{content: '韩国' + text, description: '你要找“韩国美女”吗？'}
		]);
	}
	else if(text == '微博') {
		suggest([
			{content: '新浪' + text, description: '新浪' + text},
			{content: '腾讯' + text, description: '腾讯' + text},
			{content: '搜狐' + text, description: '搜索' + text},
		]);
	}
	else {
		suggest([
			{content: '百度搜索 ' + text, description: '百度搜索 ' + text},
			{content: '谷歌搜索 ' + text, description: '谷歌搜索 ' + text},
		]);
	}
});

// 当用户接收关键字建议时触发
chrome.omnibox.onInputEntered.addListener((text) => {
    console.log('inputEntered: ' + text);
	if(!text) return;
	var href = '';
    if(text.endsWith('美女')) href = 'http://image.baidu.com/search/index?tn=baiduimage&ie=utf-8&word=' + text;
	else if(text.startsWith('百度搜索')) href = 'https://www.baidu.com/s?ie=UTF-8&wd=' + text.replace('百度搜索 ', '');
	else if(text.startsWith('谷歌搜索')) href = 'https://www.google.com.tw/search?q=' + text.replace('谷歌搜索 ', '');
	else href = 'https://www.baidu.com/s?ie=UTF-8&wd=' + text;
	openUrlCurrentTab(href);
});

// 预留一个方法给popup调用
function testBackground() {
	alert('你好，我是background！');
}

// 是否显示图片
var showImage;
chrome.storage.sync.get({showImage: true}, function(items) {
	showImage = items.showImage;
});